package com.nowcoder.code.hjnc;

import com.algorithm.model.ListNode;
import com.algorithm.model.ListNodeService;


public class NC50 {

    public static void main(String[] args) {

        ListNode listNode = ListNodeService.getByArray(new int[]{1, 2, 3, 4, 5});
        ListNodeService.print(new NC50().reverseKGroup(listNode, 2));

    }


    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode result = head;
        ListNode[] listNodes = new ListNode[k];
        int i = 0;
        for (; i < k && result != null; i++) {
            listNodes[i] = result;
            result = result.next;
        }

        if (i < k) {
            return head;
        } else {
            result = listNodes[k - 1];
        }

        ListNode last = new ListNode(-1);
        while (head != null) {
            i = 0;
            for (; i < k && head != null; i++) {
                listNodes[i] = head;
                head = head.next;
            }
            if (i < k) {
                if (i > 0) {
                    last.next = listNodes[0];
                }
                return result;
            }
            i--;
            last.next = listNodes[i];
            for (; i > 0; i--) {
                listNodes[i].next = listNodes[i - 1];
            }
            last = listNodes[i];
            listNodes[i].next = null;

        }
        return result;
    }

}
